# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import os
import sys
import re
import chardet

# 获取当前脚本所在目录的上两级目录（即 D:\code\mygit\xscript）
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
# 将项目根目录添加到系统路径中
sys.path.append(project_root)

# 现在可以正常导入 base 目录下的模块
from base import re_base
from base import file_base

def replace_file_handler(content):
    # print(f"文件内容替换前:\n{content}\n{'-'*80}")
    newc = re_base.replace_dynamic_cast(content)
    # print(f"文件内容替换后:\n{newc}\n{'-'*80}")
    return newc
def re_file_handler(file_path, noqt_conf):
    file_base.replace_in_file(file_path, replace_file_handler)


def replace_by_conf_handler(file_path, conf):
    def replace_content(content):
        for key, value in conf.items():
            content = content.replace(key, value)
        return content

    file_base.replace_in_file(file_path, replace_content)
def replace_by_conf(noqt_conf, directory, target_extensions):
    conf = file_base.read_key_value_conf(noqt_conf)
    
    file_base.read_files_with_extension(directory, target_extensions, replace_by_conf_handler, conf)

# 测试示例 
# python noqt.py D:\work\code\extra_log\testlog .cpp .h .cc .hh

if __name__ == "__main__":
    noqt_conf = project_root + "/noqt/noqt.ini"
    print(f"替换配置文件路径: {noqt_conf}")
    
    directory = r'D:\work\code\extra_log\testlog'
    target_extensions = ['.cpp', '.h', '.cc', '.hh']

    # 读取命令行参数
    if len(sys.argv) > 1:
        directory = sys.argv[1]
    if len(sys.argv) > 2:
        target_extensions = sys.argv[2:]

    # 确保扩展名以点开头
    target_extensions = [ext if ext.startswith('.') else f'.{ext}' for ext in target_extensions]

    print(f"处理目录: {directory}")
    print(f"目标后缀: {target_extensions}")

    
    if True:
        file_base.read_files_with_extension(directory, target_extensions, re_file_handler, noqt_conf)

    if False:
        replace_by_conf(noqt_conf, directory, target_extensions)
